<template>
  <div>
    <div>
      <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
        <el-form-item label="试卷名称" prop="paperName">
          <el-input v-model="queryParams.paperName" placeholder="请输入试卷名称" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="试卷类型" prop="paperType">
              <el-select v-model="queryParams.paperType" placeholder="请选择类型" clearable style="flex: 1" @change="changeType">
                <el-option label="理论" :value="1" />
                <el-option label="实践" :value="2" />
              </el-select>
            </el-form-item>
        <el-form-item label="考核课程" prop="courseId">
          <el-select v-model="queryParams.courseId" placeholder="请选择考核课程" clearable>
            <el-option v-for="dict in data.queryCourseList" :key="dict.courseId" :label="dict.courseName" :value="dict.courseId" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="Plus" @click="handleAdd"
            v-hasPermi="['examination:paper:add']">新增</el-button>
        </el-col>
        <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="paperList" @selection-change="handleSelectionChange">
        <el-table-column label="试卷名称" align="center" prop="paperName" width="200px" />
         <el-table-column label="试卷类型" align="center" prop="paperStatus" width="100px">
          <template #default="scope">
            <el-tag v-if="scope.row.paperType === 1" effect="dark">理论</el-tag>
            <el-tag v-if="scope.row.paperType === 2" effect="dark">实践</el-tag>
          </template>
        </el-table-column>
        <!-- <el-table-column label="所属专业" align="center" prop="majorName" /> -->
        <el-table-column label="课程名称" align="center" prop="courseName" />
        <!-- <el-table-column label="课程所属分类" align="center" prop="courseCategory">
          <template #default="scope">
            <span v-if="scope.row.courseCategory === '0'">公共课程</span>
            <span v-if="scope.row.courseCategory === '1'">专业课程</span>
          </template>
        </el-table-column> -->

        <el-table-column label="修改时间" align="center" prop="updateTime" />
        <el-table-column label="考试时长(分钟)" align="center" prop="paperTime" width="120px" />
        <el-table-column label="试卷状态" align="center" prop="paperStatus" width="100px">
          <template #default="scope">
            <el-tag v-if="scope.row.paperStatus === 1" effect="dark">未发布</el-tag>
            <el-tag v-if="scope.row.paperStatus === 2" effect="dark">已发布</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="试卷总分" align="center" prop="paperScoreCount" />

        <el-table-column label="创建者" align="center" prop="paperAuthorName" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="238px">
          <template #default="scope">
            <el-button v-if="scope.row.paperStatus === 1" link type="primary" icon="Promotion"
              @click="handlePublish(scope.row)">发布</el-button>

            <el-button v-if="scope.row.paperStatus === 1" link type="primary" icon="Edit"
              @click="handleUpdate(scope.row)" v-hasPermi="['examination:paper:edit']">修改</el-button>

            <el-button link type="primary" icon="View" @click="handleView(scope.row)">预览</el-button>

            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
              v-hasPermi="['examination:paper:detele']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="getList" />
    </div>
    <el-dialog title="预览试券" v-model="openPreview" width="820px" append-to-body destroy-on-close>
      <Paper :paperDetails="data.currentSelectedPaperShow" :paperId="data.currentSelectedPaperShow.paperId"
        :isPreview="true" />
    </el-dialog>
  </div>
</template>

<script setup name="Paper">
import {
  listPaper,
  delPaper,
  publishPaper,
  showPaperList,
  listQuestion
} from "@/api/testCenter/paper";
import { queryCourseList } from '@/api/analyse.js'
import Paper from "./Paper";

const { proxy } = getCurrentInstance();

const paperList = ref([]);
const open = ref(false);
const openPreview = ref(false);

const loading = ref(true);
const questionLoading = ref(true);

const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const questionTotal = ref(0);
const title = ref("");

const emits = defineEmits(["add", "edit"]);

const data = reactive({
  paperAuthorName: "",
  courseList: [],
  queryCourseList: [],
  majorList: [],
  // 手动生成题类型分数
  gradeList: [],
  // 手动生成所选题
  eduPaperDetailList: [],
  currentSelectedPaperShow: {},
  questionList: [],
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    paperName: null,
    majorId: null,
    courseId: null,
    paperAuthorId: null,
    paperTime: null,
    paperScoreCount: null,
    passScore: null,
    paperStatus: null,
    danXuanScore: null,
    duoXuanScore: null,
    panDuanScore: null,
    deleted: null,
    paperType:null
  },
  paperScoreCount: "",
});

const { queryParams, form } = toRefs(data);


/** 查询试卷管理列表 */
function getList() {
  loading.value = true;
  listPaper(queryParams.value).then((response) => {
    paperList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 试券发布 */
function handlePublish(row) {
  const _paperIds = row.paperId || ids.value;
  proxy.$modal
    .confirm("发布之后的试卷将不能修改，是否确定发布？")
    .then(function () {
      return publishPaper({
        paperId: _paperIds,
      });
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("发布成功");
    })
    .catch(() => { });
}


async function handleView(row) {

  const result = await showPaperList(row.paperId);
  if (result && result.code === 200 && result.data) {
    data.currentSelectedPaperShow = result.data;
    openPreview.value = true;
  }
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.paperId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  emits('add')
}

function handleUpdate(row) {
  emits('edit', row)
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _paperIds = row.paperId || ids.value;
  proxy.$modal
    .confirm("是否确认删除该数据项？")
    .then(function () {
      return delPaper(_paperIds);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => { });
}


function getQuestionList() {
  questionLoading.value = true;

  listQuestion({
    ...data.questionQueryParams,
    courseId: form.value.courseId || "",
    majorId: form.value.majorId || "",
  }).then((response) => {
    data.questionList = response.rows;
    questionTotal.value = response.total;
    questionLoading.value = false;
  });
}

async function init() {
  const [courseRes] = await Promise.all([queryCourseList(), getList()]);
  console.log("🚀 ~ init ~ courseRes:", courseRes)

  if (courseRes.code === 200 && courseRes.rows && courseRes.rows.length) {
    data.queryCourseList = courseRes.rows;
  }
}

init();
</script>

<style lang="scss" scoped>
.my-el-input-number[data-unit] {
  --el-input-number-unit-offset-x: 35px;
  position: relative;
}

.my-el-input-number[data-unit]::after {
  content: attr(data-unit);
  height: 100%;
  display: flex;
  align-items: center;
  position: absolute;
  padding-right: 20px;
  font-size: 14px;
  top: 0;
  right: var(--el-input-number-unit-offset-x);
  color: #aaa;
}

.my-el-input-number[data-unit] .el-input__inner {
  padding-left: 30px;
  padding-right: calc(var(--el-input-number-unit-offset-x) + 12px);
}
</style>

<style lang="scss" scoped>
.dialog-footer {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

:deep(.pagination-container) {
  margin-top: 28px !important;
  height: 48px !important;
}

:deep(.paper__dialog-left .el-form-item) {
  margin-bottom: 25px;
}

:deep(.paper__dialog-left .el-divider) {
  margin-bottom: 38px;
  margin-top: 45px;
}

.paper {
  &__tips {
    font-size: 14px;
    color: #333;
  }

  &__dialog {
    display: flex;
    flex-direction: row;
    border-bottom: 1px solid #f2f3f5;
  }

  &__dialog-left {
    width: 390px;
    border-right: 1px solid #f2f3f5;
    padding-right: 20px;
    padding-bottom: 270px;
  }

  &__dialog-right {
    position: relative;
    flex: 1;
    padding-left: 14px;
    padding-right: 14px;
  }

  &__dialog-right-tier {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 10;
    background-color: rgba($color: #e6e8eb, $alpha: 0.39);
  }

  &__list-count {
    display: flex;
    align-items: center;
    flex-direction: column;
    justify-content: center;
  }
}
</style>
